package com.ruoyi.heytalk.netty.impl;

import cn.hutool.core.util.IdUtil;
import com.ruoyi.common.constant.heytalk.CommonConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.heytalk.ImChatLog;
import com.ruoyi.common.core.domain.heytalk.ImUser;
import com.ruoyi.common.core.domain.heytalk.netty.ChatMsg;
import com.ruoyi.common.core.domain.heytalk.netty.DataType;
import com.ruoyi.common.core.domain.heytalk.netty.UserChannelUtils;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.JsonUtils;
import com.ruoyi.common.utils.RedisUtils;
import com.ruoyi.common.utils.heytalk.ByteBufUtils;
import com.ruoyi.heytalk.netty.IChatForwardHandlerService;
import com.ruoyi.heytalk.service.IImChatLogService;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * netty消息转发处理接口实现
 * @author zhusy
 * @since 2022/1/1
 */
@Slf4j
@Service
public class ChatForwardHandlerServiceImpl implements IChatForwardHandlerService {

    @Autowired
    private IImChatLogService chatLogService;

    @Override
    public AjaxResult<Object> chat(List<String> userIdList, String msgType, Boolean isCache, Boolean isSave, ChatMsg chatMsg) {
        try {
            userIdList.stream().forEach(userId -> {
                Channel toUserChannel = UserChannelUtils.getChannel(userId);
                DataType dataType = DataType.builder().type(msgType).data(chatMsg).build();
                //接收方不存在或socket不在线
                if (!Objects.isNull(toUserChannel) && UserChannelUtils.hasLogin(toUserChannel)) {
                    ChannelFuture cf = toUserChannel.writeAndFlush(ByteBufUtils.getByteBuf(dataType));
                    log.info("cf.isSuccess值:{}", cf.isSuccess());
                }
                if (isCache) {
                    log.info("消息存入了缓存");
                    //保存在缓存中
                    RedisUtils.setCacheObject(CommonConstants.CHAT_MESSAGE + userId + CommonConstants.PLUS + IdUtil.fastSimpleUUID(), dataType);
                }
            });
            if (isSave) {
                //保存到聊天记录中
                chatLogService.save(ImChatLog.builder()
                        .userId(chatMsg.getFromId())
                        .data(chatMsg.getData())
                        .chatType(msgType)
                        .options(JsonUtils.toJsonString(chatMsg.getOptions()))
                        .type(chatMsg.getType())
                        .fullData(JsonUtils.toJsonString(chatMsg)).build());
            }
            return AjaxResult.success(new Object());
        } catch (Exception e) {
            throw new ServiceException("消息转发失败，请稍后重试");
        }
    }

}
